//
//  XMLParser.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/1/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "XMLParser.h"

@implementation XMLParser

static GDataXMLDocument *dataDoc=nil;
static GDataXMLDocument *dataTempDoc=nil;
static NSString *dataFileName=nil;
static NSString *dataXMLRoot=@"//TransIntelligence/SignalAssistor";

//@synthesize fileName = _fileName;
//- (void) dealloc
//{
//    [dataFileName release];
//    [super dealloc];
//}
+ (BOOL) changeDataXML:(NSString *)xmlFileName
{
    dataFileName=[xmlFileName retain];
    [PropertyReadingWritingClass writeXMLFileName:dataFileName];
    return [XMLParser loadDataXML];
}
+ (BOOL) loadDataXML
{
    dataFileName=[[PropertyReadingWritingClass readXMLFileName] retain];
    if (!dataFileName) {
        dataFileName=@"signal_assistor_app";
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                      NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsPath = [documentsDirectory
                               stringByAppendingPathComponent:[dataFileName stringByAppendingPathExtension:@"xml"]];
    NSLog(@"%@ \n", documentsPath);
    if(![[NSFileManager defaultManager] fileExistsAtPath:documentsPath])
    {
        
        [XMLParser createNewProject];
//        [PropertyReadingWritingClass writeXMLFileName:@"signal_assistor_app"];
//        dataFileName=@@"signal_assistor_app";
//        documentsPath = [documentsDirectory
//                         stringByAppendingPathComponent:[dataFileName stringByAppendingPathExtension:@"xml"]];
    }
    
    
    NSData *xmlData = [[[NSMutableData alloc] initWithContentsOfFile:documentsPath]autorelease];    
    NSError *error;
    dataDoc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
    if (error) {
        NSLog(@"%@ \n", dataDoc.rootElement);
        return FALSE;
    }else
    {
        return TRUE;
    }
    
    
}

+ (BOOL) loadTempXML
{
    NSString *filePath = [XMLParser dataTempFilePath];
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        return FALSE;
    }
    NSData *xmlData = [[[NSMutableData alloc] initWithContentsOfFile:filePath]autorelease];
    NSError *error;
    dataTempDoc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
    if (error) {
        NSLog(@"%@ \n", dataDoc.rootElement);
        return FALSE;
    }else
    {
        return TRUE;
    }
}

+ (NSString *)dataTempFilePath;
{
    return [[NSBundle mainBundle] pathForResource:@"dataTempXML" ofType:@"xml"];
}

+ (BOOL) saveDataXML
{
    
  
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsPath = [documentsDirectory stringByAppendingPathComponent:[dataFileName stringByAppendingPathExtension:@"xml"]];
//    NSLog(@"Saving xml data to %@...", documentsPath);
//    NSString* formattedXML = [dataDoc.rootElement XMLStringWithOptions:NSXMLNodePrettyPrint];
    return [dataDoc.XMLData writeToFile:documentsPath atomically:YES];
}
+ (BOOL) createNewProject
{
    if (!dataFileName) {
        return FALSE;
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsPath = [documentsDirectory
                               stringByAppendingPathComponent:[dataFileName stringByAppendingPathExtension:@"xml"]];
    NSLog(@"Saving xml data to %@...", documentsPath);
    if (!dataTempDoc) {
        [XMLParser loadTempXML];
    }
    return [dataTempDoc.XMLData writeToFile:documentsPath atomically:YES];
    
}






//Operations of agency
+ (BOOL) createAgency: (Agency *) agency
{
    if (!agency || !agency.agencyID) {
        return FALSE;
    }
    
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies"];    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString1 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
    GDataXMLElement *agencyElement=[GDataXMLElement elementWithName:@"Agency"];
    GDataXMLElement *agencyIDElement=[GDataXMLElement elementWithName:@"AgencyID" stringValue:agency.agencyID];
    GDataXMLElement *agencyNameElement=[GDataXMLElement elementWithName:@"AgencyName" stringValue:agency.agencyName];
    GDataXMLElement *syncTimeElement=[GDataXMLElement elementWithName:@"SyncTime" stringValue:@"01:00 AM"];
    GDataXMLElement *baseTimeOffsetElement=[GDataXMLElement elementWithName:@"BaseTimeOffset" stringValue:@"0"];
    GDataXMLElement *subSystemsElement=[GDataXMLElement elementWithName:@"SubSystems"];
    
    [agencyElement addChild:agencyIDElement];
    [agencyElement addChild:agencyNameElement];
    [agencyElement addChild:syncTimeElement];
    [agencyElement addChild:baseTimeOffsetElement];
    [agencyElement addChild:subSystemsElement];
    [[parentElements objectAtIndex:0] addChild:agencyElement];
    return [self saveDataXML];
}
+ (BOOL) removeAgency: (Agency *) agency
{
    if (!agency || !agency.agencyID) {
        return FALSE;
    }
    
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies"];    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString1 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
    
    xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies/Agency[AgencyID=\""];
    NSString *xPathString2=[xPathString1 stringByAppendingString:agency.agencyID];    
    NSString *xPathString3=[xPathString2 stringByAppendingString:@"\"]"];
    NSArray *childElements=[dataDoc nodesForXPath:xPathString3 error:nil];
    if (childElements.count<=0) {
        return FALSE;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}

+ (NSArray *) getAgencyList
{
    NSString *xPathString=[dataXMLRoot stringByAppendingString:@"/Agencies/Agency"];    
    NSArray *agencyElementList;
    if (dataDoc!=nil) {
        agencyElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    NSMutableArray *agencyList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement *agencyElement in agencyElementList) {
        Agency * agency=[[[Agency alloc] init] autorelease];
        NSArray *IDArray=[agencyElement elementsForName:@"AgencyID"];
        if (IDArray.count>0) {
            [agency setAgencyID:[[IDArray objectAtIndex:0] stringValue]];
            
        }
        NSArray * nameArray=[agencyElement elementsForName:@"AgencyName"];
        if (nameArray.count>0) {
            [agency setAgencyName:[[nameArray objectAtIndex:0] stringValue]];
        }
        NSArray * syncTimeArray=[agencyElement elementsForName:@"SyncTime"];
        if (syncTimeArray.count>0) {
            [agency setSyncTime:[[syncTimeArray objectAtIndex:0] stringValue]];
        }
        NSArray * baseTimeOffsetArray=[agencyElement elementsForName:@"BaseTimeOffset"];
        if (baseTimeOffsetArray.count>0) {
            [agency setBaseTimeOffset:[[baseTimeOffsetArray objectAtIndex:0] stringValue]];
        }
//        NSArray * subSystemsArray=[agencyElement elementsForName:@"SubSystems"];
//        if (subSystemsArray.count>0) {
//            NSMutableArray *subSystemIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subSystemsElement=[subSystemsArray objectAtIndex:0];
//            NSArray *subSystemArray=[subSystemsElement elementsForName:@"SubSystem"];
//            for (GDataXMLElement *subSystem in subSystemArray) {
//                NSString *subSystemID=[[[subSystem elementsForName:@"SubSystemID"] objectAtIndex:0] stringValue];
//                [subSystemIDList addObject:subSystemID];
//                
//            }
//            [agency setSubSystemIDList:subSystemIDList];
//            
//        }
        [agencyList addObject:agency];
        
    }
    return agencyList;
}
+ (Agency *) getAgencyByAgencyID: (NSString *) agencyID
{
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies/Agency[AgencyID=\""];
    NSString *xPathString2=[xPathString1 stringByAppendingString:agencyID];    
    NSString *xPathString3=[xPathString2 stringByAppendingString:@"\"]"];
    NSArray *agencyElementList;
    if (dataDoc!=nil) {
        agencyElementList=[dataDoc nodesForXPath:xPathString3 error:nil];
    }else {
        return nil;
    }
    for (GDataXMLElement *agencyElement in agencyElementList) {
        Agency * agency=[[[Agency alloc] init] autorelease];
        NSArray *IDArray=[agencyElement elementsForName:@"AgencyID"];
        if (IDArray.count>0) {
            [agency setAgencyID:[[IDArray objectAtIndex:0] stringValue]];
            
        }
        NSArray * nameArray=[agencyElement elementsForName:@"AgencyName"];
        if (nameArray.count>0) {
            [agency setAgencyName:[[nameArray objectAtIndex:0] stringValue]];
        }
        NSArray * syncTimeArray=[agencyElement elementsForName:@"SyncTime"];
        if (syncTimeArray.count>0) {
            [agency setSyncTime:[[syncTimeArray objectAtIndex:0] stringValue]];
        }
        NSArray * baseTimeOffsetArray=[agencyElement elementsForName:@"BaseTimeOffset"];
        if (baseTimeOffsetArray.count>0) {
            [agency setBaseTimeOffset:[[baseTimeOffsetArray objectAtIndex:0] stringValue]];
        }
//        NSArray * subSystemsArray=[agencyElement elementsForName:@"SubSystems"];
//        if (subSystemsArray.count>0) {
//            NSMutableArray *subSystemIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subSystemsElement=[subSystemsArray objectAtIndex:0];
//            NSArray *subSystemArray=[subSystemsElement elementsForName:@"SubSystem"];
//            for (GDataXMLElement *subSystem in subSystemArray) {
//                NSString *subSystemID=[[[subSystem elementsForName:@"SubSystemID"] objectAtIndex:0] stringValue];
//                [subSystemIDList addObject:subSystemID];
//                
//            }
//            [agency setSubSystemIDList:subSystemIDList];
//            
//        }
        return agency;
        
    }
    return nil;
}
+ (BOOL) updateAgency: (Agency *) agency
{
    if (!agency || !agency.agencyID) {
        return FALSE;
    }
    
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies"];    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString1 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
     NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]",agency.agencyID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *childrenElementList;
    childrenElementList=[dataDoc nodesForXPath:xPathString error:nil];
    if (childrenElementList.count<=0) {
        return [XMLParser createAgency:agency];
    }
    for (GDataXMLElement *childElement in childrenElementList) {
        GDataXMLElement *childNameElement=[[childElement elementsForName:@"AgencyName"] objectAtIndex:0];
        [childNameElement setStringValue:agency.agencyName];
        GDataXMLElement *syncTimeElement=[[childElement elementsForName:@"SyncTime"] objectAtIndex:0];
        [syncTimeElement setStringValue:agency.syncTime];
        GDataXMLElement *baseTimeOffset=[[childElement elementsForName:@"BaseTimeOffset"] objectAtIndex:0];
        [baseTimeOffset setStringValue:agency.baseTimeOffset];
        
        //subSystemList is not updated in this function, but handled by the functions of SubSyctem Entity.
        
    }
    return [self saveDataXML];
    
}

+ (NSString *) createAgencyID
{
    NSArray * agencyList=[self getAgencyList];
    int maxID=-1;
    for (int i=0; i<agencyList.count; i++) {
        Agency *agency=[agencyList objectAtIndex:i];
        int agencyIDValue=[agency.agencyID intValue];
        if (maxID<agencyIDValue) {
            maxID=agencyIDValue;
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

//Operations of subSystem
+ (BOOL) createSubSystem:(SubSystem *)subSystem
{
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies/Agency[AgencyID=\""];
    NSString *xPathString2=[xPathString1 stringByAppendingString:agencyID];    
    NSString *xPathString3=[xPathString2 stringByAppendingString:@"\"]/SubSystems"];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString3 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
    GDataXMLElement *subSystemElement=[GDataXMLElement elementWithName:@"SubSystem"];
    GDataXMLElement *subSystemIDElement=[GDataXMLElement elementWithName:@"SubSystemID" stringValue:subSystem.subSystemID];
    GDataXMLElement *subSystemNameElement=[GDataXMLElement elementWithName:@"SubSystemName" stringValue:subSystem.subSystemName];
    GDataXMLElement *regionElement=[GDataXMLElement elementWithName:@"Region"];
    GDataXMLElement *intersectionsElement=[GDataXMLElement elementWithName:@"Intersections"];
    GDataXMLElement *timingPatternsElement=[GDataXMLElement elementWithName:@"TimingPatterns"];
    GDataXMLElement *linksElement=[GDataXMLElement elementWithName:@"Links"];
    GDataXMLElement *regionCenterElement=[GDataXMLElement elementWithName:@"Center"];
    GDataXMLElement *regionCenterLatitudeElement=[GDataXMLElement elementWithName:@"CenterLatitude" stringValue:@"0"];
    GDataXMLElement *regionCenterLongitudeElement=[GDataXMLElement elementWithName:@"CenterLongitude" stringValue:@"0"];
    [regionCenterElement addChild:regionCenterLatitudeElement];
    [regionCenterElement addChild:regionCenterLongitudeElement];
    [regionElement addChild:regionCenterElement];
    GDataXMLElement *regionRangeElement=[GDataXMLElement elementWithName:@"Range"];
    GDataXMLElement *regionRangeWidthElement=[GDataXMLElement elementWithName:@"RangeWidth" stringValue:@"5000"];
    GDataXMLElement *regionRangeLengthElement=[GDataXMLElement elementWithName:@"RangeLength" stringValue:@"5000"];
    [regionRangeElement addChild:regionRangeWidthElement];
    [regionRangeElement addChild:regionRangeLengthElement];
    [regionElement addChild:regionRangeElement];    
    
    [subSystemElement addChild:subSystemIDElement];
    [subSystemElement addChild:subSystemNameElement];
    [subSystemElement addChild:regionElement];
    [subSystemElement addChild:intersectionsElement];
    [subSystemElement addChild:linksElement];
    [subSystemElement addChild:timingPatternsElement];
    
    [[parentElements objectAtIndex:0] addChild:subSystemElement];
    return [self saveDataXML];
}
+ (BOOL) removeSubSystem:(SubSystem *)subSystem
{
    NSString *subSystemID=subSystem.subSystemID;
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *xPathString1=[dataXMLRoot stringByAppendingString:@"/Agencies/Agency[AgencyID=\""];
    NSString *xPathString2=[xPathString1 stringByAppendingString:agencyID];
    
    NSString *xPathString3=[xPathString2 stringByAppendingString:@"\"]/SubSystems"];
    
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString3 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
    
    xPathString1=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystemID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString1 error:nil];
    if (childElements.count<=0) {
        return FALSE;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}
+ (NSArray *) getSubSystemListofAgency:(Agency *)agency
{
    NSString *agencyID=agency.agencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem",agencyID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    NSMutableArray *resultList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement *resultElement in resultElementList) {
        SubSystem * result=[[[SubSystem alloc] init] autorelease];
        if ([[resultElement elementsForName:@"SubSystemID"] count]>0) {
            [result setSubSystemID:[[[resultElement elementsForName:@"SubSystemID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"SubSystemName"] count]>0) {
            [result setSubSystemName:[[[resultElement elementsForName:@"SubSystemName"] objectAtIndex:0] stringValue]];
        }
        NSArray * regionElementsArray=[resultElement elementsForName:@"Region"];
        CLLocationCoordinate2D center={0,0};
        result.region=MKCoordinateRegionMakeWithDistance(center,5000,5000);
        if (regionElementsArray.count>0) {
            float centerLatitude=0;
            float centerLongitude=0;
            float width=5000;
            float length=5000;
            GDataXMLElement *regionElement=[regionElementsArray objectAtIndex:0];
            if ([[regionElement elementsForName:@"Center"] count]>0) {
                GDataXMLElement *regionCenterElement=[[regionElement elementsForName:@"Center"] objectAtIndex:0];
                if ([[regionCenterElement elementsForName:@"CenterLatitude"] count]>0) {
                    centerLatitude=[[[[regionCenterElement elementsForName:@"CenterLatitude"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionCenterElement elementsForName:@"CenterLongitude"] count]>0) {
                    centerLongitude=[[[[regionCenterElement elementsForName:@"CenterLongitude"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            if ([[regionElement elementsForName:@"Range"] count]>0) {
                GDataXMLElement *regionRangeElement=[[regionElement elementsForName:@"Range"] objectAtIndex:0];
                if ([[regionRangeElement elementsForName:@"RangeWidth"] count]>0) {
                    width=[[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue] floatValue];
                    NSLog(@"\n%@",[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue]);
                }
                if ([[regionRangeElement elementsForName:@"RangeLength"] count]>0) {
                    length=[[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue] floatValue];
                    NSLog(@"\n%@",[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue]);
                }
            }
            CLLocationCoordinate2D c={centerLatitude,centerLongitude};
            MKCoordinateSpan s={length,width};
            result.region=MKCoordinateRegionMake(c, s);
        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"TimingPatterns"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"TimingPattern"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setTimingPatternIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Intersections"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Intersection"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"IntersectionID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setIntersectionIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Links"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Link"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"LinkID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setLinkIDList:subElementIDList];
//                
//            }
//        }
        result.parentAgencyID=agency.agencyID;
        [resultList addObject:result];
        
    }
    return resultList;
}

+ (NSArray *) getSubSystemListbyAgencyID:(NSString *)agencyID
{
//    NSString *agencyID=agency.agencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem",agencyID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    NSMutableArray *resultList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement *resultElement in resultElementList) {
        SubSystem * result=[[[SubSystem alloc] init] autorelease];
        if ([[resultElement elementsForName:@"SubSystemID"] count]>0) {
            [result setSubSystemID:[[[resultElement elementsForName:@"SubSystemID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"SubSystemName"] count]>0) {
            [result setSubSystemName:[[[resultElement elementsForName:@"SubSystemName"] objectAtIndex:0] stringValue]];
        }
        NSArray * regionElementsArray=[resultElement elementsForName:@"Region"];
        CLLocationCoordinate2D center={0,0};
        result.region=MKCoordinateRegionMakeWithDistance(center,5000,5000);
        if (regionElementsArray.count>0) {
            float centerLatitude=0;
            float centerLongitude=0;
            float width=5000;
            float length=5000;
            GDataXMLElement *regionElement=[regionElementsArray objectAtIndex:0];
            if ([[regionElement elementsForName:@"Center"] count]>0) {
                GDataXMLElement *regionCenterElement=[[regionElement elementsForName:@"Center"] objectAtIndex:0];
                if ([[regionCenterElement elementsForName:@"CenterLatitude"] count]>0) {
                    centerLatitude=[[[[regionCenterElement elementsForName:@"CenterLatitude"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionCenterElement elementsForName:@"CenterLongitude"] count]>0) {
                    centerLongitude=[[[[regionCenterElement elementsForName:@"CenterLongitude"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            if ([[regionElement elementsForName:@"Range"] count]>0) {
                GDataXMLElement *regionRangeElement=[[regionElement elementsForName:@"Range"] objectAtIndex:0];
                if ([[regionRangeElement elementsForName:@"RangeWidth"] count]>0) {
                    width=[[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue] floatValue];
                    NSLog(@"\n%@",[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue]);
                }
                if ([[regionRangeElement elementsForName:@"RangeLength"] count]>0) {
                    length=[[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue] floatValue];
                    NSLog(@"\n%@",[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue]);
                }
            }
            CLLocationCoordinate2D c={centerLatitude,centerLongitude};
            MKCoordinateSpan s={length,width};
            result.region=MKCoordinateRegionMake(c, s);
        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"TimingPatterns"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"TimingPattern"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setTimingPatternIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Intersections"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Intersection"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"IntersectionID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setIntersectionIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Links"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Link"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"LinkID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setLinkIDList:subElementIDList];
//                
//            }
//        }
        result.parentAgencyID=agencyID;
        [resultList addObject:result];
        
    }
    return resultList;
}
+ (SubSystem *) getSubSystemofAgency:(NSString *)subSystemID agency:(Agency *)agency
{
    NSString *agencyID=agency.agencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystemID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    for (GDataXMLElement *resultElement in resultElementList) {
        SubSystem * result=[[[SubSystem alloc] init] autorelease];
        if ([[resultElement elementsForName:@"SubSystemID"] count]>0) {
            [result setSubSystemID:[[resultElement elementsForName:@"SubSystemID"] objectAtIndex:0]];
        }
        
        if ([[resultElement elementsForName:@"SubSystemName"] count]>0) {
            [result setSubSystemName:[[resultElement elementsForName:@"SubSystemName"] objectAtIndex:0]];
        }
        
        NSArray * regionElementsArray=[resultElement elementsForName:@"Region"];
        CLLocationCoordinate2D center={0,0};
        result.region=MKCoordinateRegionMakeWithDistance(center,5000,5000);
        if (regionElementsArray.count>0) {
            double centerLatitude=0;
            double centerLongitude=0;
            double width=5000;
            double length=5000;
            GDataXMLElement *regionElement=[regionElementsArray objectAtIndex:0];
            if ([[regionElement elementsForName:@"Center"] count]>0) {
                GDataXMLElement *regionCenterElement=[[regionElement elementsForName:@"Center"] objectAtIndex:0];
                if ([[regionCenterElement elementsForName:@"CenterLatitude"] count]>0) {
                    centerLatitude=[[[[regionCenterElement elementsForName:@"CenterLatitude"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionCenterElement elementsForName:@"CenterLongitude"] count]>0) {
                    centerLongitude=[[[[regionCenterElement elementsForName:@"CenterLongitude"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            if ([[regionElement elementsForName:@"Range"] count]>0) {
                GDataXMLElement *regionRangeElement=[[regionElement elementsForName:@"Range"] objectAtIndex:0];
                if ([[regionRangeElement elementsForName:@"RangeWidth"] count]>0) {
                    width=[[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionRangeElement elementsForName:@"RangeLength"] count]>0) {
                    length=[[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            CLLocationCoordinate2D c={centerLatitude,centerLongitude};
            MKCoordinateSpan s={length,width};
            result.region=MKCoordinateRegionMake(c, s);
        }

//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"TimingPatterns"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"TimingPattern"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setTimingPatternIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Intersections"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Intersection"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"IntersectionID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setIntersectionIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Links"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Link"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"LinkID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setLinkIDList:subElementIDList];
//                
//            }
//        }
        [result setParentAgencyID:agency.agencyID];
        return result;
        
    }
    return nil;
}

+ (SubSystem *) getSubSystembyAgencyID:(NSString *)subSystemID agencyID:(NSString *)agencyID
{
//    NSString *agencyID=agency.agencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystemID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    for (GDataXMLElement *resultElement in resultElementList) {
        SubSystem * result=[[[SubSystem alloc] init] autorelease];
        if ([[resultElement elementsForName:@"SubSystemID"] count]>0) {
            [result setSubSystemID:[[resultElement elementsForName:@"SubSystemID"] objectAtIndex:0]];
        }
        
        if ([[resultElement elementsForName:@"SubSystemName"] count]>0) {
            [result setSubSystemName:[[resultElement elementsForName:@"SubSystemName"] objectAtIndex:0]];
        }
        
        NSArray * regionElementsArray=[resultElement elementsForName:@"Region"];
        CLLocationCoordinate2D center={0,0};
        result.region=MKCoordinateRegionMakeWithDistance(center,5000,5000);
        if (regionElementsArray.count>0) {
            double centerLatitude=0;
            double centerLongitude=0;
            double width=5000;
            double length=5000;
            GDataXMLElement *regionElement=[regionElementsArray objectAtIndex:0];
            if ([[regionElement elementsForName:@"Center"] count]>0) {
                GDataXMLElement *regionCenterElement=[[regionElement elementsForName:@"Center"] objectAtIndex:0];
                if ([[regionCenterElement elementsForName:@"CenterLatitude"] count]>0) {
                    centerLatitude=[[[[regionCenterElement elementsForName:@"CenterLatitude"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionCenterElement elementsForName:@"CenterLongitude"] count]>0) {
                    centerLongitude=[[[[regionCenterElement elementsForName:@"CenterLongitude"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            if ([[regionElement elementsForName:@"Range"] count]>0) {
                GDataXMLElement *regionRangeElement=[[regionElement elementsForName:@"Range"] objectAtIndex:0];
                if ([[regionRangeElement elementsForName:@"RangeWidth"] count]>0) {
                    width=[[[[regionRangeElement elementsForName:@"RangeWidth"] objectAtIndex:0] stringValue] floatValue];
                }
                if ([[regionRangeElement elementsForName:@"RangeLength"] count]>0) {
                    length=[[[[regionRangeElement elementsForName:@"RangeLength"] objectAtIndex:0] stringValue] floatValue];
                }
            }
            CLLocationCoordinate2D c={centerLatitude,centerLongitude};
            MKCoordinateSpan s={length,width};
            result.region=MKCoordinateRegionMake(c, s);
        }
        
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"TimingPatterns"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"TimingPattern"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setTimingPatternIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Intersections"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Intersection"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"IntersectionID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setIntersectionIDList:subElementIDList];
//                
//            }
//        }
//        {
//            NSArray * subElementsArray=[resultElement elementsForName:@"Links"];
//            if (subElementsArray.count>0) {
//                NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//                GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//                NSArray *subIDElementArray=[subElement elementsForName:@"Link"];
//                for (GDataXMLElement *subIDElement in subIDElementArray) {
//                    NSString *subID=[[[subIDElement elementsForName:@"LinkID"] objectAtIndex:0] stringValue];
//                    [subElementIDList addObject:subID];
//                    
//                }
//                [result setLinkIDList:subElementIDList];
//                
//            }
//        }
        [result setParentAgencyID:agencyID];
        return result;
        
    }
    return nil;
}

+(BOOL) updateSubSystem: (SubSystem *) subSystem
{
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *xPathString1=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem",agencyID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString1 error:nil];
    if (parentElements.count<=0) {
        return FALSE;
    }
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystem.subSystemID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *childrenElementList;
    childrenElementList=[dataDoc nodesForXPath:xPathString error:nil];
    BOOL elementExist=NO;
    for (GDataXMLElement *childElement in childrenElementList) {
        NSString *childElementID=[[[childElement elementsForName:@"SubSystemID"] objectAtIndex:0] stringValue];
        if (![childElementID isEqualToString:subSystem.subSystemID]) {
            continue;
        }
        elementExist=YES;
        GDataXMLElement *childNameElement=[[childElement elementsForName:@"SubSystemName"] objectAtIndex:0];
        [childNameElement setStringValue:subSystem.subSystemName];
        if ([[childElement elementsForName:@"Region"] count]>0) {
            GDataXMLElement *regionElement=[[childElement elementsForName:@"Region"] objectAtIndex:0];
            [childElement removeChild:regionElement];
            
            
        }
        {
            GDataXMLElement *regionElement=[GDataXMLElement elementWithName:@"Region"];
            GDataXMLElement *regionCenterElement=[GDataXMLElement elementWithName:@"Center"];
            GDataXMLElement *regionCenterLatitudeElement=[GDataXMLElement elementWithName:@"CenterLatitude" stringValue:[NSString stringWithFormat:@"%f",subSystem.region.center.latitude]];
            GDataXMLElement *regionCenterLongitudeElement=[GDataXMLElement elementWithName:@"CenterLongitude" stringValue:[NSString stringWithFormat:@"%f",subSystem.region.center.longitude]];
            [regionCenterElement addChild:regionCenterLatitudeElement];
            [regionCenterElement addChild:regionCenterLongitudeElement];
            [regionElement addChild:regionCenterElement];
            GDataXMLElement *regionRangeElement=[GDataXMLElement elementWithName:@"Range"];
            GDataXMLElement *regionRangeWidthElement=[GDataXMLElement elementWithName:@"RangeWidth" stringValue:[NSString stringWithFormat:@"%f",subSystem.region.span.longitudeDelta]];
            GDataXMLElement *regionRangeLengthElement=[GDataXMLElement elementWithName:@"RangeLength" stringValue:[NSString stringWithFormat:@"%f",subSystem.region.span.latitudeDelta]];
            [regionRangeElement addChild:regionRangeWidthElement];
            [regionRangeElement addChild:regionRangeLengthElement];
            [regionElement addChild:regionRangeElement];
            
            [childElement addChild:regionElement];
        }
        
    }
    if (!elementExist) {
        return [XMLParser createSubSystem:subSystem];
    }else
    {
        return [self saveDataXML];
    }
    
}

+ (NSString *) createSubSystemID:(Agency *)agency
{
    NSArray * elementList=[self getSubSystemListofAgency:agency];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        SubSystem *element=[elementList objectAtIndex:i];
        if (maxID<[element.subSystemID intValue]) {
            maxID=[element.subSystemID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}


//Operations of timingPattern
+ (BOOL) createTimingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    NSString *subSystemID=timingPattern.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    GDataXMLElement *timingPatternElement=[GDataXMLElement elementWithName:@"TimingPattern"];
    GDataXMLElement *timingPatternIDElement=[GDataXMLElement elementWithName:@"TimingPatternID" stringValue:timingPattern.timingPatternID];
    GDataXMLElement *timingPatternName=[GDataXMLElement elementWithName:@"TimingPatternName" stringValue:timingPattern.timingPatternName];
    GDataXMLElement *cycleLengthElement=[GDataXMLElement elementWithName:@"TimingPatternCycleLength" stringValue:@"100"];
    GDataXMLElement *signalsElement=[GDataXMLElement elementWithName:@"Signals"];
    
    GDataXMLElement *timeRangesElement=[GDataXMLElement elementWithName:@"TimeRanges"];
    NSMutableArray *timeRangeList=timingPattern.timeRangeList;
    for (int i=0; i<timeRangeList.count; i++) {
        TimeRange *timeRange=[timeRangeList objectAtIndex:i];
        GDataXMLElement *timeRangeElement=[GDataXMLElement elementWithName:@"TimeRange"];
        GDataXMLElement *beginTimeElement=[GDataXMLElement elementWithName:@"BeginTime" stringValue:timeRange.beginTime];
        GDataXMLElement *endTimeElement=[GDataXMLElement elementWithName:@"EndTime" stringValue:timeRange.endTime];
        [timeRangeElement addChild:beginTimeElement];
        [timeRangeElement addChild:endTimeElement];
        [timeRangesElement addChild:timeRangeElement];
    }
    
    
    [timingPatternElement addChild:timingPatternIDElement];
    [timingPatternElement addChild:timingPatternName];
    [timingPatternElement addChild:cycleLengthElement];
    [timingPatternElement addChild:timeRangesElement];
    [timingPatternElement addChild:signalsElement];
//    [timingPatternElement addChild:linksElement];
    [[parentElements objectAtIndex:0] addChild:timingPatternElement];
    NSArray * intersectionList=[self getIntersectionList:agencyID subSystemID:subSystemID];
    for (Intersection *intersection in intersectionList) {
        Signal *signal=[[[NEMASignal alloc] initWithCycleLength:timingPattern.cycleLength] autorelease];
        [signal setSignalID:intersection.intersectionID];
        //    [signal setCycleLength:self.timingPattern.cycleLength];
        [signal setOffset:@"0"];
        [signal setSignalName:intersection.intersectionName];
        [XMLParser createSignal:signal];
    }
    return [self saveDataXML];
}
+ (TimingPattern *) duplicateTimingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    Agency *agency=[XMLParser getAgencyByAgencyID:agencyID];
    NSString *subSystemID=timingPattern.parentSubSystemID;
    SubSystem *subSystem=[XMLParser getSubSystemofAgency:subSystemID agency:agency];
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    GDataXMLElement *timingPatternElement=[GDataXMLElement elementWithName:@"TimingPattern"];
    NSString *newTimingPatternID=[XMLParser createTimingPatternID:subSystem];
    GDataXMLElement *timingPatternIDElement=[GDataXMLElement elementWithName:@"TimingPatternID" stringValue:timingPattern.timingPatternID];
    GDataXMLElement *timingPatternName=[GDataXMLElement elementWithName:@"TimingPatternName" stringValue:timingPattern.timingPatternName];
    GDataXMLElement *cycleLengthElement=[GDataXMLElement elementWithName:@"TimingPatternCycleLength" stringValue:timingPattern.cycleLength];
    GDataXMLElement *signalsElement=[GDataXMLElement elementWithName:@"Signals"];
    
    GDataXMLElement *timeRangesElement=[GDataXMLElement elementWithName:@"TimeRanges"];
    NSMutableArray *timeRangeList=timingPattern.timeRangeList;
    for (int i=0; i<timeRangeList.count; i++) {
        TimeRange *timeRange=[timeRangeList objectAtIndex:i];
        GDataXMLElement *timeRangeElement=[GDataXMLElement elementWithName:@"TimeRange"];
        GDataXMLElement *beginTimeElement=[GDataXMLElement elementWithName:@"BeginTime" stringValue:timeRange.beginTime];
        GDataXMLElement *endTimeElement=[GDataXMLElement elementWithName:@"EndTime" stringValue:timeRange.endTime];
        [timeRangeElement addChild:beginTimeElement];
        [timeRangeElement addChild:endTimeElement];
        [timeRangesElement addChild:timeRangeElement];
    }
    
    
    [timingPatternElement addChild:timingPatternIDElement];
    [timingPatternElement addChild:timingPatternName];
    [timingPatternElement addChild:cycleLengthElement];
    [timingPatternElement addChild:timeRangesElement];
    [timingPatternElement addChild:signalsElement];
    //    [timingPatternElement addChild:linksElement];
    [[parentElements objectAtIndex:0] addChild:timingPatternElement];
    NSArray * signalList=[self getSignalList:agencyID subSystemID:subSystemID timingPatternID:timingPattern.timingPatternID];
    for (int n=0; n<signalList.count; n++) {
        Signal *signal=[signalList objectAtIndex:n];
        [XMLParser createSignal:signal];
    }

     [self saveDataXML];
    return [XMLParser getTimingPatternofSubSystem:newTimingPatternID subSystem:subSystem];
}
+ (BOOL) removeTimingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    NSString *subSystemID=timingPattern.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]",agencyID,subSystemID,timingPattern.timingPatternID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}
+ (NSArray *) getTimingPatternListofSubSystem:(SubSystem *) subSystem
{
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern",agencyID,subSystemID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    NSMutableArray *resultList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement *resultElement in resultElementList) {
        TimingPattern * result=[[[TimingPattern alloc] init] autorelease];
        if ([[resultElement elementsForName:@"TimingPatternID"] count]>0) {
            [result setTimingPatternID:[[[resultElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternName"] count]>0) {
            [result setTimingPatternName:[[[resultElement elementsForName:@"TimingPatternName"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternCycleLength"] count]>0) {
            [result setCycleLength:[[[resultElement elementsForName:@"TimingPatternCycleLength"] objectAtIndex:0] stringValue]];
        }
//        NSArray * subElementsArray=[resultElement elementsForName:@"Signals"];
//        if (subElementsArray.count>0) {
//            NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//            NSArray *subIDElementArray=[subElement elementsForName:@"Signal"];
//            for (GDataXMLElement *subIDElement in subIDElementArray) {
//                NSString *subID=[[[subIDElement elementsForName:@"SignalID"] objectAtIndex:0] stringValue];
//                [subElementIDList addObject:subID];
//                
//            }
//            [result setSignalIDList:subElementIDList];
//            
//        }
        
        NSArray * subElementsArray=[resultElement elementsForName:@"TimeRanges"];
        if (subElementsArray.count>0) {
            NSMutableArray *subElementList=[[[NSMutableArray alloc] init] autorelease];
            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
            NSArray *subIDElementArray=[subElement elementsForName:@"TimeRange"];
            for (GDataXMLElement *subIDElement in subIDElementArray) {
                NSString *beginTime=[[[subIDElement elementsForName:@"BeginTime"] objectAtIndex:0] stringValue];
                NSString *endTime=[[[subIDElement elementsForName:@"EndTime"] objectAtIndex:0] stringValue];
                TimeRange * timeRange=[[[TimeRange alloc] init] autorelease];
                [timeRange setBeginTime:beginTime];
                [timeRange setEndTime:endTime];
                [subElementList addObject:timeRange];
                
            }
            [result setTimeRangeList:subElementList];
            
            
        }
        result.parentAgencyID=agencyID;
        result.parentSubSystemID=subSystemID;
        [resultList addObject:result];
        
    }
    return resultList;
}
+ (NSArray *) getTimingPatternList:(NSString *)subSystemID agencyID:(NSString *)agencyID
{
//    NSString *agencyID=subSystem.parentAgencyID;
//    NSString *subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern",agencyID,subSystemID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    NSMutableArray *resultList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement *resultElement in resultElementList) {
        TimingPattern * result=[[[TimingPattern alloc] init] autorelease];
        if ([[resultElement elementsForName:@"TimingPatternID"] count]>0) {
            [result setTimingPatternID:[[[resultElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternName"] count]>0) {
            [result setTimingPatternName:[[[resultElement elementsForName:@"TimingPatternName"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternCycleLength"] count]>0) {
            [result setCycleLength:[[[resultElement elementsForName:@"TimingPatternCycleLength"] objectAtIndex:0] stringValue]];
        }
//        NSArray * subElementsArray=[resultElement elementsForName:@"Signals"];
//        if (subElementsArray.count>0) {
//            NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//            NSArray *subIDElementArray=[subElement elementsForName:@"Signal"];
//            for (GDataXMLElement *subIDElement in subIDElementArray) {
//                NSString *subID=[[[subIDElement elementsForName:@"SignalID"] objectAtIndex:0] stringValue];
//                [subElementIDList addObject:subID];
//                
//            }
//            [result setSignalIDList:subElementIDList];
//            
//        }
        
        NSArray * subElementsArray=[resultElement elementsForName:@"TimeRanges"];
        if (subElementsArray.count>0) {
            NSMutableArray *subElementList=[[[NSMutableArray alloc] init] autorelease];
            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
            NSArray *subIDElementArray=[subElement elementsForName:@"TimeRange"];
            for (GDataXMLElement *subIDElement in subIDElementArray) {
                NSString *beginTime=[[[subIDElement elementsForName:@"BeginTime"] objectAtIndex:0] stringValue];
                NSString *endTime=[[[subIDElement elementsForName:@"EndTime"] objectAtIndex:0] stringValue];
                TimeRange * timeRange=[[[TimeRange alloc] init] autorelease];
                [timeRange setBeginTime:beginTime];
                [timeRange setEndTime:endTime];
                [subElementList addObject:timeRange];
                
            }
            [result setTimeRangeList:subElementList];
            
            
        }
        result.parentAgencyID=agencyID;
        result.parentSubSystemID=subSystemID;
        [resultList addObject:result];
        
    }
    return resultList;
}
+ (TimingPattern *) getTimingPatternofSubSystem:(NSString *)timingPatternID subSystem:(SubSystem *)subSystem
{
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]",agencyID,subSystemID,timingPatternID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    for (GDataXMLElement *resultElement in resultElementList) {
        TimingPattern * result=[[[TimingPattern alloc] init] autorelease];
        if ([[resultElement elementsForName:@"TimingPatternID"] count]>0) {
            [result setTimingPatternID:[[[resultElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternName"] count]>0) {
            [result setTimingPatternName:[[[resultElement elementsForName:@"TimingPatternName"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternCycleLength"] count]>0) {
            [result setCycleLength:[[[resultElement elementsForName:@"TimingPatternCycleLength"] objectAtIndex:0] stringValue]];
        }
//        NSArray * subElementsArray=[resultElement elementsForName:@"Signals"];
//        if (subElementsArray.count>0) {
//            NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//            NSArray *subIDElementArray=[subElement elementsForName:@"Signal"];
//            for (GDataXMLElement *subIDElement in subIDElementArray) {
//                NSString *subID=[[[subIDElement elementsForName:@"SignalID"] objectAtIndex:0] stringValue];
//                [subElementIDList addObject:subID];
//                
//            }
//            [result setSignalIDList:subElementIDList];
//            
//        }
        
        NSArray * subElementsArray=[resultElement elementsForName:@"TimeRanges"];
        if (subElementsArray.count>0) {
            NSMutableArray *subElementList=[[[NSMutableArray alloc] init] autorelease];
            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
            NSArray *subIDElementArray=[subElement elementsForName:@"TimeRange"];
            for (GDataXMLElement *subIDElement in subIDElementArray) {
                NSString *beginTime=[[[subIDElement elementsForName:@"BeginTime"] objectAtIndex:0] stringValue];
                NSString *endTime=[[[subIDElement elementsForName:@"EndTime"] objectAtIndex:0] stringValue];
                TimeRange * timeRange=[[[TimeRange alloc] init] autorelease];
                [timeRange setBeginTime:beginTime];
                [timeRange setEndTime:endTime];
                [subElementList addObject:timeRange];
                
            }
            [result setTimeRangeList:subElementList];
            
        }
        result.parentAgencyID=agencyID;
        result.parentSubSystemID=subSystemID;
        return result;
        
    }
    return nil;

}

+ (TimingPattern *) getTimingPattern:(NSString *)timingPatternID subSystemID:(NSString *)subSystemID agencyID:(NSString *)agencyID
{
//    NSString *agencyID=subSystem.parentAgencyID;
//    NSString *subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]",agencyID,subSystemID,timingPatternID];
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *resultElementList;
    if (dataDoc!=nil) {
        resultElementList=[dataDoc nodesForXPath:xPathString error:nil];
    }else {
        return nil;
    }
    for (GDataXMLElement *resultElement in resultElementList) {
        TimingPattern * result=[[[TimingPattern alloc] init] autorelease];
        if ([[resultElement elementsForName:@"TimingPatternID"] count]>0) {
            [result setTimingPatternID:[[[resultElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternName"] count]>0) {
            [result setTimingPatternName:[[[resultElement elementsForName:@"TimingPatternName"] objectAtIndex:0] stringValue]];
        }
        
        if ([[resultElement elementsForName:@"TimingPatternCycleLength"] count]>0) {
            [result setCycleLength:[[[resultElement elementsForName:@"TimingPatternCycleLength"] objectAtIndex:0] stringValue]];
        }
//        NSArray * subElementsArray=[resultElement elementsForName:@"Signals"];
//        if (subElementsArray.count>0) {
//            NSMutableArray *subElementIDList=[[[NSMutableArray alloc] init] autorelease];
//            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
//            NSArray *subIDElementArray=[subElement elementsForName:@"Signal"];
//            for (GDataXMLElement *subIDElement in subIDElementArray) {
//                NSString *subID=[[[subIDElement elementsForName:@"SignalID"] objectAtIndex:0] stringValue];
//                [subElementIDList addObject:subID];
//                
//            }
//            [result setSignalIDList:subElementIDList];
//            
//        }
        
        NSArray * subElementsArray=[resultElement elementsForName:@"TimeRanges"];
        if (subElementsArray.count>0) {
            NSMutableArray *subElementList=[[[NSMutableArray alloc] init] autorelease];
            GDataXMLElement *subElement=[subElementsArray objectAtIndex:0];
            NSArray *subIDElementArray=[subElement elementsForName:@"TimeRange"];
            for (GDataXMLElement *subIDElement in subIDElementArray) {
                NSString *beginTime=[[[subIDElement elementsForName:@"BeginTime"] objectAtIndex:0] stringValue];
                NSString *endTime=[[[subIDElement elementsForName:@"EndTime"] objectAtIndex:0] stringValue];
                TimeRange * timeRange=[[[TimeRange alloc] init] autorelease];
                [timeRange setBeginTime:beginTime];
                [timeRange setEndTime:endTime];
                [subElementList addObject:timeRange];
                
            }
            [result setTimeRangeList:subElementList];
            
        }
        result.parentAgencyID=agencyID;
        result.parentSubSystemID=subSystemID;
        return result;
        
    }
    return nil;
    
}

+ (BOOL) updateTimingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    NSString *subSystemID=timingPattern.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]",agencyID,subSystemID,timingPattern.timingPatternID];
    
    NSLog(@"\n %@!!", xPathString);
    
    NSArray *childrenElementList;
    childrenElementList=[dataDoc nodesForXPath:xPathString error:nil];
    BOOL elementExist=NO;
    for (GDataXMLElement *childElement in childrenElementList) {
        NSString *childElementID=[[[childElement elementsForName:@"TimingPatternID"] objectAtIndex:0] stringValue];
        if (![childElementID isEqualToString:timingPattern.timingPatternID]) {
            continue;
        }
        elementExist=YES;
        GDataXMLElement *childNameElement=[[childElement elementsForName:@"TimingPatternName"] objectAtIndex:0];
        [childNameElement setStringValue:timingPattern.timingPatternName];
        
        GDataXMLElement *childCycleLengthElement=[[childElement elementsForName:@"TimingPatternCycleLength"] objectAtIndex:0];
        [childCycleLengthElement setStringValue:timingPattern.cycleLength];
        
        GDataXMLElement *timeRangesElement=[[childElement elementsForName:@"TimeRanges"] objectAtIndex:0];
        NSArray *timeRangeArray=[timeRangesElement elementsForName:@"TimeRange"];
        for (int i=0; i<timeRangeArray.count; i++) {
            [timeRangesElement removeChild:[timeRangeArray objectAtIndex:i]];
        }
        NSMutableArray *timeRangeList=timingPattern.timeRangeList;
        for (int i=0; i<timeRangeList.count; i++) {
            TimeRange *timeRange=[timeRangeList objectAtIndex:i];
            GDataXMLElement *timeRangeElement=[GDataXMLElement elementWithName:@"TimeRange"];
            GDataXMLElement *beginTimeElement=[GDataXMLElement elementWithName:@"BeginTime" stringValue:timeRange.beginTime];
            GDataXMLElement *endTimeElement=[GDataXMLElement elementWithName:@"EndTime" stringValue:timeRange.endTime];
            [timeRangeElement addChild:beginTimeElement];
            [timeRangeElement addChild:endTimeElement];
            [timeRangesElement addChild:timeRangeElement];
        }
        
//        [self saveDataXML];
        
        
    }
    if (!elementExist) {
        return [XMLParser createTimingPattern:timingPattern];
    }
    return [self saveDataXML];
    
}

+ (NSString *) createTimingPatternID:(SubSystem *)subSystem
{
    NSArray * elementList=[self getTimingPatternListofSubSystem:subSystem];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        TimingPattern *element=[elementList objectAtIndex:i];
        if (maxID<[element.timingPatternID intValue]) {
            maxID=[element.timingPatternID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

//Operations of intersections
+ (BOOL)createIntersection:(Intersection *)intersection
{
    NSString *agencyID = intersection.parentAgencyID;
    NSString *subSystemID=intersection.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections",agencyID,subSystemID];
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (parentElements.count<=0) {
        
        //if there is no intersections node, reate one
        xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystemID];
        parentElements=[dataDoc nodesForXPath:xPathString error:nil];
        GDataXMLElement *intersectionsElement=[GDataXMLElement elementWithName:@"Intersections"];
        if (parentElements.count<=0) {
            return false;
        }
        [[parentElements objectAtIndex:0] addChild:intersectionsElement];
        
        
        xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections",agencyID,subSystemID];
        parentElements=[dataDoc nodesForXPath:xPathString error:nil];
        if (parentElements.count<=0) {
            return false;
        }
    }
    GDataXMLElement *intersectionElement=[GDataXMLElement elementWithName:@"Intersection"];
    GDataXMLElement *intersectionIDElement=[GDataXMLElement elementWithName:@"IntersectionID" stringValue:intersection.intersectionID];
    GDataXMLElement *intersectionNameElement=[GDataXMLElement elementWithName:@"IntersectionName" stringValue:intersection.intersectionName];
    
    [intersectionElement addChild:intersectionIDElement];
    [intersectionElement addChild:intersectionNameElement];
    {
        GDataXMLElement *coordinateElement=[GDataXMLElement elementWithName:@"IntersectionCoordinate"];
        GDataXMLElement *coordinateLatitudeElement=[GDataXMLElement elementWithName:@"Latitude" stringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.latitude]];
        GDataXMLElement *coordinateLongitudeElement=[GDataXMLElement elementWithName:@"Longitude" stringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.longitude]];
        [coordinateElement addChild:coordinateLatitudeElement];
        [coordinateElement addChild:coordinateLongitudeElement];
        [intersectionElement addChild:coordinateElement];
    }
    [[parentElements objectAtIndex:0] addChild:intersectionElement];
    
    NSArray *timingPatternList=[self getTimingPatternList:subSystemID agencyID:agencyID];
    for (TimingPattern *timingPattern in timingPatternList) {
        //        TimingPattern *timingPattern=[timePatternList objectAtIndex:i];
        Signal *signal=[[[NEMASignal alloc] initWithCycleLength:timingPattern.cycleLength] autorelease];
        [signal setSignalID:intersection.intersectionID];
        //    [signal setCycleLength:self.timingPattern.cycleLength];
        [signal setOffset:@"0"];
        [signal setSignalName:intersection.intersectionName];
        [XMLParser createSignal:signal];
    }
    
    return [self saveDataXML];
    
}
+ (BOOL) removeIntersection:(Intersection *)intersection;
{
    NSString *intersectionID=intersection.intersectionID;
    NSString *agencyID=intersection.parentAgencyID;
    NSString *subSystemID=intersection.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection[IntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    NSArray *timingPatternList=[self getTimingPatternList:subSystemID agencyID:agencyID];
    for (TimingPattern *timingPattern in timingPatternList) {
        [self removeSignalbyIDs:intersectionID agencyID:agencyID subSystemID:subSystemID timingPatternID:timingPattern.timingPatternID];
    }
    
    return [self saveDataXML];
}
+ (NSArray *) getIntersectionList:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection",agencyID,subSystemID];
    
    NSArray *intersectionElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * intersectionList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * intersectionElement in intersectionElementList) {
        Intersection *intersection=[[[Intersection alloc] init] autorelease];
        NSArray *elementArray=[intersectionElement elementsForName:@"IntersectionID"];
        if (elementArray.count>0) {
            [intersection setIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionName"];
        if (elementArray.count>0) {
            [intersection setIntersectionName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionCoordinate"];
        if (elementArray.count>0) {
            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
            elementArray=[coordinateElement elementsForName:@"Latitude"];
            double latitude=0;
            if (elementArray.count>0) {
                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            elementArray=[coordinateElement elementsForName:@"Longitude"];
            double longitude=0;
            if (elementArray.count>0) {
                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            CLLocationCoordinate2D coordinate={latitude,longitude};
            [intersection setIntersectionCoordinate:coordinate];
            
        }
        
        
        [intersection setParentAgencyID:agencyID];
        [intersection setParentSubSystemID:subSystemID];
        [intersectionList addObject:intersection];
        
        
    }
    return intersectionList;
    
}

+ (NSArray *) getIntersectionListofSubSystem:(SubSystem *)subSystem
{
    NSString *subSystemID=subSystem.subSystemID;
    NSString *agencyID=subSystem.parentAgencyID;
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection",agencyID,subSystemID];
    
    NSArray *intersectionElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * intersectionList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * intersectionElement in intersectionElementList) {
        Intersection *intersection=[[[Intersection alloc] init] autorelease];
        NSArray *elementArray=[intersectionElement elementsForName:@"IntersectionID"];
        if (elementArray.count>0) {
            [intersection setIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionName"];
        if (elementArray.count>0) {
            [intersection setIntersectionName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionCoordinate"];
        if (elementArray.count>0) {
            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
            elementArray=[coordinateElement elementsForName:@"Latitude"];
            double latitude=0;
            if (elementArray.count>0) {
                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            elementArray=[coordinateElement elementsForName:@"Longitude"];
            double longitude=0;
            if (elementArray.count>0) {
                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            CLLocationCoordinate2D coordinate={latitude,longitude};
            [intersection setIntersectionCoordinate:coordinate];
            
        }
        
        [intersection setParentAgencyID:agencyID];
        [intersection setParentSubSystemID:subSystemID];
        
        [intersectionList addObject:intersection];
        
        
    }
    return intersectionList;
    
}

+ (Intersection *) getIntersection:(NSString *)intersectionID agencyID:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection[IntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    NSArray *intersectionElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    //    NSMutableArray * intersectionList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * intersectionElement in intersectionElementList) {
        Intersection *intersection=[[[Intersection alloc] init] autorelease];
        NSArray *elementArray=[intersectionElement elementsForName:@"IntersectionID"];
        if (elementArray.count>0) {
            [intersection setIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionName"];
        if (elementArray.count>0) {
            [intersection setIntersectionName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionCoordinate"];
        if (elementArray.count>0) {
            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
            elementArray=[coordinateElement elementsForName:@"Latitude"];
            double latitude=0;
            if (elementArray.count>0) {
                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            elementArray=[coordinateElement elementsForName:@"Longitude"];
            double longitude=0;
            if (elementArray.count>0) {
                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            CLLocationCoordinate2D coordinate={latitude,longitude};
            [intersection setIntersectionCoordinate:coordinate];
            
        }
        
        [intersection setParentAgencyID:agencyID];
        [intersection setParentSubSystemID:subSystemID];
        
        return intersection;
        
        
    }
    
    
    return nil;
    
}

+ (Intersection *) getIntersectionofSubSystem:(NSString *)intersectionID subSystem:(SubSystem *)subSystem
{
    NSString *subSystemID=subSystem.subSystemID;
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection[IntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    NSArray *intersectionElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    //    NSMutableArray * intersectionList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * intersectionElement in intersectionElementList) {
        Intersection *intersection=[[[Intersection alloc] init] autorelease];
        NSArray *elementArray=[intersectionElement elementsForName:@"IntersectionID"];
        if (elementArray.count>0) {
            [intersection setIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionName"];
        if (elementArray.count>0) {
            [intersection setIntersectionName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[intersectionElement elementsForName:@"IntersectionCoordinate"];
        if (elementArray.count>0) {
            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
            elementArray=[coordinateElement elementsForName:@"Latitude"];
            double latitude=0;
            if (elementArray.count>0) {
                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            elementArray=[coordinateElement elementsForName:@"Longitude"];
            double longitude=0;
            if (elementArray.count>0) {
                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
            }
            CLLocationCoordinate2D coordinate={latitude,longitude};
            [intersection setIntersectionCoordinate:coordinate];
            
        }
        
        [intersection setParentAgencyID:agencyID];
        [intersection setParentSubSystemID:subSystemID];
        
        return intersection;
        
        
    }
    
    
    return nil;
    
}
+ (BOOL) updateIntersection:(Intersection *)intersection
{
    NSString *subSystemID=intersection.parentSubSystemID;
    NSString *agencyID=intersection.parentAgencyID;
    if (!link) {
        return false;
    }
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Intersections/Intersection[IntersectionID=\"%@\"]",agencyID,subSystemID,intersection.intersectionID];
    NSArray *elements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (elements.count<=0) {
        [self createIntersection:intersection];
    }
    for (GDataXMLElement *element in elements) {
        if ([[element elementsForName:@"IntersectionName"] count]>0) {
            [[[element elementsForName:@"IntersectionName"] objectAtIndex:0] setStringValue:intersection.intersectionName];
            
        }
        if ([[element elementsForName:@"IntersectionCoordinate"] count]>0) {
            GDataXMLElement *coordinateElement=[[element elementsForName:@"IntersectionCoordinate"] objectAtIndex:0];
            if ([[coordinateElement elementsForName:@"Latitude"] count]>0) {
                [[[coordinateElement elementsForName:@"Latitude"] objectAtIndex:0] setStringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.latitude]];
            }
            if ([[coordinateElement elementsForName:@"Longitude"] count]>0) {
                [[[coordinateElement elementsForName:@"Longitude"] objectAtIndex:0] setStringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.longitude]];
            }
            //            [[[element elementsForName:@"Coordinate"] objectAtIndex:0] setStringValue:signal.signalName];
        }else {
            GDataXMLElement *coordinateElement=[GDataXMLElement elementWithName:@"IntersectionCoordinate"];
            GDataXMLElement *coordinateLatitudeElement=[GDataXMLElement elementWithName:@"Latitude" stringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.latitude]];
            GDataXMLElement *coordinateLongitudeElement=[GDataXMLElement elementWithName:@"Longitude" stringValue:[NSString stringWithFormat:@"%f",intersection.intersectionCoordinate.longitude]];
            [coordinateElement addChild:coordinateLatitudeElement];
            [coordinateElement addChild:coordinateLongitudeElement];
            [element addChild:coordinateElement];
            //            [element addChild:signalCoordinateElement];
            
        }
        
    }
    
    
    return [self saveDataXML];
    
    
}

+ (NSString *) createIntersectionID:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSArray * elementList=[self getIntersectionList:agencyID subSystemID:subSystemID ];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Intersection *element=[elementList objectAtIndex:i];
        if (maxID<[element.intersectionID intValue]) {
            maxID=[element.intersectionID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

+ (NSString *) createIntersectionIDofSubSystem:(SubSystem *)subSystem
{
    NSString *subSystemID=subSystem.subSystemID;
    NSString *agencyID=subSystem.parentAgencyID;
    NSArray * elementList=[self getIntersectionList:agencyID subSystemID:subSystemID ];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Intersection *element=[elementList objectAtIndex:i];
        if (maxID<[element.intersectionID intValue]) {
            maxID=[element.intersectionID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

//Operations of links
+ (BOOL)createLink:(Link *)link 
{
    NSString *agencyID=link.parentAgencyID;
    NSString *subSystemID=link.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links",agencyID,subSystemID];
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (parentElements.count<=0) {
        xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]",agencyID,subSystemID];
        parentElements=[dataDoc nodesForXPath:xPathString error:nil];
        GDataXMLElement *linksElement=[GDataXMLElement elementWithName:@"Links"];
        if (parentElements.count<=0) {
            return false;
        }
        [[parentElements objectAtIndex:0] addChild:linksElement];
        xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links",agencyID,subSystemID];
        parentElements=[dataDoc nodesForXPath:xPathString error:nil];
        if (parentElements.count<=0) {
            return false;
        }
    }
    GDataXMLElement *linkElement=[GDataXMLElement elementWithName:@"Link"];
    GDataXMLElement *linkIDElement=[GDataXMLElement elementWithName:@"LinkID" stringValue:link.linkID];
    GDataXMLElement *linkNameElement=[GDataXMLElement elementWithName:@"LinkName" stringValue:link.linkName];
    GDataXMLElement * fromSignalIDElement=[GDataXMLElement elementWithName:@"FromIntersectionID" stringValue:link.fromIntersectionID];
    GDataXMLElement * toSignalIDElement=[GDataXMLElement elementWithName:@"ToIntersectionID" stringValue:link.toIntersectionID];
    GDataXMLElement * linkDirectionElement=[GDataXMLElement elementWithName:@"LinkDirection" stringValue:link.linkDirection];
    GDataXMLElement * linkLengthElement=[GDataXMLElement elementWithName:@"Length" stringValue:link.length];
    GDataXMLElement * linkSpeedLimitElement=[GDataXMLElement elementWithName:@"SpeedLimit" stringValue:link.speedLimit];
    
    
    [linkElement addChild:linkIDElement];
    [linkElement addChild:linkNameElement];
    [linkElement addChild:fromSignalIDElement];
    [linkElement addChild:toSignalIDElement];
    [linkElement addChild:linkDirectionElement];
    [linkElement addChild:linkLengthElement];
    [linkElement addChild:linkSpeedLimitElement];
    [[parentElements objectAtIndex:0] addChild:linkElement];
    
    return [self saveDataXML];
    
    
}
+ (BOOL) removeLink:(Link *) link
{
    NSString *linkID=link.linkID;
    NSString *agencyID=link.parentAgencyID;
    NSString *subSystemID=link.parentSubSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links",agencyID,subSystemID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[LinkID=\"%@\"]",agencyID,subSystemID,linkID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}
+ (NSArray *) getLinkList:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link",agencyID,subSystemID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}

+ (NSArray *) getLinkListofSubSystem:(SubSystem *)subSystem
{
    NSString *agencyID=subSystem.parentAgencyID;
    NSString *subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link",agencyID,subSystemID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}
+ (NSArray *)getLinkListFromIntersectionbyIDs:(NSString *)agencyID subSystemID:(NSString *)subSystemID intersectionID:(NSString *)intersectionID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[FromIntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}

+ (NSArray *)getLinkListFromIntersection:(Intersection *)intersection
{
    NSString *intersectionID=intersection.intersectionID;
    NSString *subSystemID=intersection.parentSubSystemID;
    NSString *agencyID=intersection.parentAgencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[FromIntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}

+ (NSArray *) getLinkListToIntersectionbyIDs:(NSString *)agencyID subSystemID:(NSString *)subSystemID intersectionID:(NSString *)intersectionID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[ToIntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}
+ (NSArray *) getLinkListToIntersection:(Intersection *)intersection
{
    NSString *intersectionID=intersection.intersectionID;
    NSString *subSystemID=intersection.parentSubSystemID;
    NSString *agencyID=intersection.parentAgencyID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[ToIntersectionID=\"%@\"]",agencyID,subSystemID,intersectionID];
    
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * linkList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        [linkList addObject:link];
        
        
    }
    return linkList;
    
}
+ (Link *) getLink:(NSString *)linkID agencyID:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[LinkID=\"%@\"]",agencyID,subSystemID,linkID];
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    //    NSLog(@"%@",xPathString);
    //    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        return link;
        
        
    }
    
    
    return nil;
    
}

+ (Link *) getLinkofSubSystem:(NSString *)linkID subSystem:(SubSystem *)subSystem
{
    NSString * agencyID=subSystem.parentAgencyID;
    NSString * subSystemID=subSystem.subSystemID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[LinkID=\"%@\"]",agencyID,subSystemID,linkID];
    NSArray *linkElementList=[dataDoc nodesForXPath:xPathString error:nil];
    //    NSLog(@"%@",xPathString);
    //    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * linkElement in linkElementList) {
        Link *link=[[[Link alloc] init] autorelease];
        NSArray *elementArray=[linkElement elementsForName:@"LinkID"];
        if (elementArray.count>0) {
            [link setLinkID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkName"];
        if (elementArray.count>0) {
            [link setLinkName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"FromIntersectionID"];
        if (elementArray.count>0) {
            [link setFromIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"ToIntersectionID"];
        if (elementArray.count>0) {
            [link setToIntersectionID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"LinkDirection"];
        if (elementArray.count>0) {
            [link setLinkDirection:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"Length"];
        if (elementArray.count>0) {
            [link setLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[linkElement elementsForName:@"SpeedLimit"];
        if (elementArray.count>0) {
            [link setSpeedLimit:[[elementArray objectAtIndex:0] stringValue]];
        }
        [link setParentSubSystemID:subSystemID];
        [link setParentAgencyID:agencyID];
        
        return link;
        
        
    }
    
    
    return nil;
    
}
+ (BOOL) updateLink:(Link *)link
{
    NSString* agencyID=link.parentAgencyID;
    NSString* subSystemID=link.parentSubSystemID;
    if (!link) {
        return false;
    }
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/Links/Link[LinkID=\"%@\"]",agencyID,subSystemID,link.linkID];
    NSArray *elements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (elements.count<=0) {
        [self createLink:link];
    }
    for (GDataXMLElement *element in elements) {
        if ([[element elementsForName:@"LinkName"] count]>0) {
            [[[element elementsForName:@"LinkName"] objectAtIndex:0] setStringValue:link.linkName];
            
        }
        if ([[element elementsForName:@"FromIntersectionID"] count]>0) {
            [[[element elementsForName:@"FromIntersectionID"] objectAtIndex:0] setStringValue:link.fromIntersectionID];
        }
        if ([[element elementsForName:@"ToIntersectionID"] count]>0) {
            [[[element elementsForName:@"ToIntersectionID"] objectAtIndex:0] setStringValue:link.toIntersectionID];
        }
        if ([[element elementsForName:@"LinkDirection"] count]>0) {
            [[[element elementsForName:@"LinkDirection"] objectAtIndex:0] setStringValue:link.linkDirection];
        }
        if ([[element elementsForName:@"Length"] count]>0) {
            [[[element elementsForName:@"Length"] objectAtIndex:0] setStringValue:link.length];
        }
        if ([[element elementsForName:@"SpeedLimit"] count]>0) {
            [[[element elementsForName:@"SpeedLimit"] objectAtIndex:0] setStringValue:link.speedLimit];
        }
        
        
    }
    
    
    return [self saveDataXML];
    
    
}

+ (NSString *) createLinkID:(NSString *)agencyID subSystemID:(NSString *)subSystemID
{
    NSArray * elementList=[self getLinkList:agencyID subSystemID:subSystemID ];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Link *element=[elementList objectAtIndex:i];
        if (maxID<[element.linkID intValue]) {
            maxID=[element.linkID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

+ (NSString *) createLinkIDofSubSystem:(SubSystem *)subSystem
{
    NSString * subSystemID=subSystem.subSystemID;
    NSString * agencyID=subSystem.parentAgencyID;
    NSArray * elementList=[self getLinkList:agencyID subSystemID:subSystemID ];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Link *element=[elementList objectAtIndex:i];
        if (maxID<[element.linkID intValue]) {
            maxID=[element.linkID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}




//Operations of signals
+ (BOOL)createSignal:(Signal *) signal
{
    NSString *agencyID=signal.parentAgencyID;
    NSString *subSystemID=signal.parentSubSystemID;
    NSString *timingPatternID=signal.parentTimingPatternID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals",agencyID,subSystemID,timingPatternID];      
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (parentElements.count<=0) {
        return false;
    }
    Signal * existingSignal=[self getSignal:signal.signalID agencyID:agencyID subSystemID:subSystemID timingPatternID:timingPatternID];
    if (existingSignal) {
        return false;
    }
    GDataXMLElement *signalElement=[GDataXMLElement elementWithName:@"Signal"];
    GDataXMLElement *signalIDElement=[GDataXMLElement elementWithName:@"SignalID" stringValue:signal.signalID];
    GDataXMLElement *signalNameElement=[GDataXMLElement elementWithName:@"SignalName" stringValue:signal.signalName];
//    GDataXMLElement *signalCoordinateElement=[GDataXMLElement elementWithName:@"Coordinate"];
//    GDataXMLElement *coordinateLatitudeElement=[GDataXMLElement elementWithName:@"Latitude" stringValue:[NSString stringWithFormat:@"%f",signal.coordinate.latitude]];
//    GDataXMLElement *coordinateLongitudeElement=[GDataXMLElement elementWithName:@"Longitude" stringValue:[NSString stringWithFormat:@"%f",signal.coordinate.longitude]];
//    [signalCoordinateElement addChild:coordinateLatitudeElement];
//    [signalCoordinateElement addChild:coordinateLongitudeElement];
    GDataXMLElement *signalCycleLengthElement=[GDataXMLElement elementWithName:@"CycleLength" stringValue:signal.cycleLength];
    GDataXMLElement *signalOffsetElement=[GDataXMLElement elementWithName:@"Offset" stringValue:signal.offset];
    GDataXMLElement *signalOffsetPhaseElement=[GDataXMLElement elementWithName:@"OffsetPhase" stringValue:signal.offsetPhase];
    GDataXMLElement *signalOffsetBorEElement=nil;
    if (!signal.offsetBorE||[signal.offsetBorE isEqualToString:@""]) {
        signalOffsetBorEElement=[GDataXMLElement elementWithName:@"OffsetBorE" stringValue:@"Green Begin"];

    }else {
        signalOffsetBorEElement=[GDataXMLElement elementWithName:@"OffsetBorE" stringValue:signal.offsetBorE];
    }
    
    
    GDataXMLElement *signalLocationElement=[GDataXMLElement elementWithName:@"Location" stringValue:signal.location];
    //    {
    GDataXMLElement *signalRing1Element=[GDataXMLElement elementWithName:@"Ring1"];
    GDataXMLElement *signalRing1IDElement=[GDataXMLElement elementWithName:@"RingID" stringValue:@"1"];
    GDataXMLElement *signalRing1PhasesElement=[GDataXMLElement elementWithName:@"Phases"];
    [signalRing1Element addChild:signalRing1IDElement];
    [signalRing1Element addChild:signalRing1PhasesElement];
    
    //    }
    //    {
    GDataXMLElement *signalRing2Element=[GDataXMLElement elementWithName:@"Ring2"];
    GDataXMLElement *signalRing2IDElement=[GDataXMLElement elementWithName:@"RingID" stringValue:@"2"];
    GDataXMLElement *signalRing2PhasesElement=[GDataXMLElement elementWithName:@"Phases"];
    [signalRing2Element addChild:signalRing2IDElement];
    [signalRing2Element addChild:signalRing2PhasesElement];
    //    }
    [signalElement addChild:signalIDElement];
    [signalElement addChild:signalNameElement];
//    [signalElement addChild:signalCoordinateElement];
    [signalElement addChild:signalCycleLengthElement];
    [signalElement addChild:signalOffsetElement];
    [signalElement addChild:signalOffsetPhaseElement];
    [signalElement addChild:signalOffsetBorEElement];
    [signalElement addChild:signalLocationElement];
    [signalElement addChild:signalRing1Element];
    [signalElement addChild:signalRing2Element];
    [[parentElements objectAtIndex:0] addChild:signalElement];
    [self saveDataXML];
    
    for (SignalRing* signalRing in signal.ringList) {
        for (SignalBarrierGroup *signalBarrier in signalRing.barrierList) {
            for (SignalPhase * phase in signalBarrier.phaseList) {
                if (phase.phaseID) {
                    [self createPhase:phase signal:signal];
                }
            }
        }
    }
//    if (signal.ring1.phaseList!=nil) {
//        for (int i=0; i<signal.ring1.phaseList.count; i++) {
////            [XMLParser createSignalPhase:timerGroupID signalID:signal.signalID signalRingID:@"1" signaPhase:[signal.ring1.phaseList objectAtIndex:i]];
//        }
//    }
//    if (signal.ring2.phaseList!=nil) {
//        for (int i=0; i<signal.ring2.phaseList.count; i++) {
////            [XMLParser createSignalPhase:timerGroupID signalID:signal.signalID signalRingID:@"2" signaPhase:[signal.ring2.phaseList objectAtIndex:i]];
//        }
//    }
    return true;

}
+ (BOOL) removeSignal:(Signal *) signal
{
    NSString *signalID=signal.signalID;
    NSString *agencyID=signal.parentAgencyID;
    NSString *subSystemID=signal.parentSubSystemID;
    NSString *timingPatternID=signal.parentTimingPatternID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals",agencyID,subSystemID,timingPatternID];  
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID];  
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}

+ (BOOL) removeSignalbyIDs:(NSString *)signalID agencyID:(NSString *)agencyID subSystemID:(NSString *)subSystemID timingPatternID:(NSString *)timingPatternID
{
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals",agencyID,subSystemID,timingPatternID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
}

+ (NSArray *) getSignalList:(NSString *)agencyID subSystemID:(NSString *)subSystemID timingPatternID:(NSString *)timingPatternID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal",agencyID,subSystemID,timingPatternID];
    NSLog(@"%@",xPathString);
    NSArray *signalElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * signalElement in signalElementList) {
        Signal *signal=[[[Signal alloc] init] autorelease];
        NSArray *elementArray=[signalElement elementsForName:@"SignalID"];
        if (elementArray.count>0) {
            [signal setSignalID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"SignalName"];
        if (elementArray.count>0) {
            [signal setSignalName:[[elementArray objectAtIndex:0] stringValue]];
        }
//        elementArray=[signalElement elementsForName:@"Coordinate"];
//        if (elementArray.count>0) {
//            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
//            elementArray=[coordinateElement elementsForName:@"Latitude"];
//            double latitude=0;
//            if (elementArray.count>0) {
//                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
//            }
//            elementArray=[coordinateElement elementsForName:@"Longitude"];
//            double longitude=0;
//            if (elementArray.count>0) {
//                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
//            }
//            CLLocationCoordinate2D coordinate={latitude,longitude};
//            [signal setCoordinate:coordinate];
//
//        }
        elementArray=[signalElement elementsForName:@"CycleLength"];
        if (elementArray.count>0) {
            [signal setCycleLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Offset"];
        if (elementArray.count>0) {
            [signal setOffset:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetPhase"];
        if (elementArray.count>0) {
            [signal setOffsetPhase:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetBorE"];
        if (elementArray.count>0) {
            [signal setOffsetBorE:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Location"];
        if (elementArray.count>0) {
            [signal setLocation:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Phases"];
        if (elementArray.count>0) {
            NSArray *phaseElementArray=[[elementArray objectAtIndex:0] elementsForName:@"Phase"];
//            NSMutableArray *phaseList=[[[NSMutableArray alloc]init]autorelease];
            for (GDataXMLElement *phaseElement in phaseElementArray) {
                SignalPhase *signalPhase=[[[SignalPhase alloc] init] autorelease];
                NSArray *phaseSubElementArray=[phaseElement elementsForName:@"PhaseID"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseID:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"PhaseMovement"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseMovement:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"GreenTime"];
                if (phaseSubElementArray) {
                    [signalPhase setGreenTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"YellowTime"];
                if (phaseSubElementArray) {
                    [signalPhase setYellowTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"AllRedTime"];
                if (phaseSubElementArray) {
                    [signalPhase setAllRedTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Ring"];
                if (phaseSubElementArray) {
                    [signalPhase setRing:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Barrier"];
                if (phaseSubElementArray) {
                    [signalPhase setBarrier:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Position"];
                if (phaseSubElementArray) {
                    [signalPhase setPosition:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                NSMutableArray * phaseList=[[[[signal.ringList objectAtIndex:[signalPhase.ring intValue]] barrierList] objectAtIndex:[signalPhase.barrier intValue]] phaseList];
                [phaseList setObject:signalPhase atIndexedSubscript:[signalPhase.position intValue]];
            }
        }
        
        signal.parentAgencyID=agencyID;
        signal.parentSubSystemID=subSystemID;
        signal.parentTimingPatternID=timingPatternID;
        [signalList addObject:signal];
        
        
    }
    return signalList;

}

+ (NSArray *) getSignalListofTimingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    NSString *subSystemID=timingPattern.parentSubSystemID;
    NSString *timingPatternID=timingPattern.timingPatternID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal",agencyID,subSystemID,timingPatternID];
    NSLog(@"%@",xPathString);
    NSArray *signalElementList=[dataDoc nodesForXPath:xPathString error:nil];
    
    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * signalElement in signalElementList) {
        Signal *signal=[[[Signal alloc] init] autorelease];
        NSArray *elementArray=[signalElement elementsForName:@"SignalID"];
        if (elementArray.count>0) {
            [signal setSignalID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"SignalName"];
        if (elementArray.count>0) {
            [signal setSignalName:[[elementArray objectAtIndex:0] stringValue]];
        }
        //        elementArray=[signalElement elementsForName:@"Coordinate"];
        //        if (elementArray.count>0) {
        //            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
        //            elementArray=[coordinateElement elementsForName:@"Latitude"];
        //            double latitude=0;
        //            if (elementArray.count>0) {
        //                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
        //            }
        //            elementArray=[coordinateElement elementsForName:@"Longitude"];
        //            double longitude=0;
        //            if (elementArray.count>0) {
        //                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
        //            }
        //            CLLocationCoordinate2D coordinate={latitude,longitude};
        //            [signal setCoordinate:coordinate];
        //
        //        }
        elementArray=[signalElement elementsForName:@"CycleLength"];
        if (elementArray.count>0) {
            [signal setCycleLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Offset"];
        if (elementArray.count>0) {
            [signal setOffset:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetPhase"];
        if (elementArray.count>0) {
            [signal setOffsetPhase:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetBorE"];
        if (elementArray.count>0) {
            [signal setOffsetBorE:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Location"];
        if (elementArray.count>0) {
            [signal setLocation:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Phases"];
        if (elementArray.count>0) {
            NSArray *phaseElementArray=[[elementArray objectAtIndex:0] elementsForName:@"Phase"];
//            NSMutableArray *phaseList=[[[NSMutableArray alloc]init]autorelease];
            for (GDataXMLElement *phaseElement in phaseElementArray) {
                SignalPhase *signalPhase=[[[SignalPhase alloc] init] autorelease];
                NSArray *phaseSubElementArray=[phaseElement elementsForName:@"PhaseID"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseID:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"PhaseMovement"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseMovement:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"GreenTime"];
                if (phaseSubElementArray) {
                    [signalPhase setGreenTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"YellowTime"];
                if (phaseSubElementArray) {
                    [signalPhase setYellowTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"AllRedTime"];
                if (phaseSubElementArray) {
                    [signalPhase setAllRedTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Ring"];
                if (phaseSubElementArray) {
                    [signalPhase setRing:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Barrier"];
                if (phaseSubElementArray) {
                    [signalPhase setBarrier:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Position"];
                if (phaseSubElementArray) {
                    [signalPhase setPosition:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                NSMutableArray * phaseList=[[[[signal.ringList objectAtIndex:[signalPhase.ring intValue]] barrierList] objectAtIndex:[signalPhase.barrier intValue]] phaseList];
                [phaseList setObject:signalPhase atIndexedSubscript:[signalPhase.position intValue]];
            }
        }
        
        signal.parentAgencyID=agencyID;
        signal.parentSubSystemID=subSystemID;
        signal.parentTimingPatternID=timingPatternID;
        [signalList addObject:signal];
        
        
    }
    return signalList;
    
}
+ (Signal *) getSignal:(NSString *) signalID agencyID:(NSString *)agencyID subSystemID:(NSString *)subSystemID timingPatternID:(NSString *)timingPatternID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID];
    NSArray *signalElementList=[dataDoc nodesForXPath:xPathString error:nil];
    NSLog(@"%@",xPathString);
    //    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * signalElement in signalElementList) {
        Signal *signal=[[[Signal alloc] init] autorelease];
        NSArray *elementArray=[signalElement elementsForName:@"SignalID"];
        if (elementArray.count>0) {
            [signal setSignalID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"SignalName"];
        if (elementArray.count>0) {
            [signal setSignalName:[[elementArray objectAtIndex:0] stringValue]];
        }
//        elementArray=[signalElement elementsForName:@"Coordinate"];
//        if (elementArray.count>0) {
//            GDataXMLElement *coordinateElement=[elementArray objectAtIndex:0];
//            elementArray=[coordinateElement elementsForName:@"Latitude"];
//            double latitude=0;
//            if (elementArray.count>0) {
//                latitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
//            }
//            elementArray=[coordinateElement elementsForName:@"Longitude"];
//            double longitude=0;
//            if (elementArray.count>0) {
//                longitude=[[[elementArray objectAtIndex:0] stringValue] floatValue];
//            }
//            CLLocationCoordinate2D coordinate={latitude,longitude};
//            [signal setCoordinate:coordinate];
//            
//        }
        elementArray=[signalElement elementsForName:@"CycleLength"];
        if (elementArray.count>0) {
            [signal setCycleLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Offset"];
        if (elementArray.count>0) {
            [signal setOffset:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetPhase"];
        if (elementArray.count>0) {
            [signal setOffsetPhase:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetBorE"];
        if (elementArray.count>0) {
            [signal setOffsetBorE:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Location"];
        if (elementArray.count>0) {
            [signal setLocation:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Phases"];
        if (elementArray.count>0) {
            NSArray *phaseElementArray=[[elementArray objectAtIndex:0] elementsForName:@"Phase"];
//            NSMutableArray *phaseList=[[[NSMutableArray alloc]init]autorelease];
            for (GDataXMLElement *phaseElement in phaseElementArray) {
                SignalPhase *signalPhase=[[[SignalPhase alloc] init] autorelease];
                NSArray *phaseSubElementArray=[phaseElement elementsForName:@"PhaseID"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseID:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"PhaseMovement"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseMovement:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"GreenTime"];
                if (phaseSubElementArray) {
                    [signalPhase setGreenTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"YellowTime"];
                if (phaseSubElementArray) {
                    [signalPhase setYellowTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"AllRedTime"];
                if (phaseSubElementArray) {
                    [signalPhase setAllRedTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Ring"];
                if (phaseSubElementArray) {
                    [signalPhase setRing:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Barrier"];
                if (phaseSubElementArray) {
                    [signalPhase setBarrier:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Position"];
                if (phaseSubElementArray) {
                    [signalPhase setPosition:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                NSMutableArray * phaseList=[[[[signal.ringList objectAtIndex:[signalPhase.ring intValue]] barrierList] objectAtIndex:[signalPhase.barrier intValue]] phaseList];
                [phaseList setObject:signalPhase atIndexedSubscript:[signalPhase.position intValue]];
            }
        }
        
        signal.parentAgencyID=agencyID;
        signal.parentSubSystemID=subSystemID;
        signal.parentTimingPatternID=timingPatternID;
        return signal;
        
        
    }
    return nil;

}

+ (Signal *) getSignalofTimingPattern:(NSString *)signalID timingPattern:(TimingPattern *)timingPattern
{
    NSString *agencyID=timingPattern.parentAgencyID;
    NSString *subSystemID=timingPattern.parentSubSystemID;
    NSString *timingPatternID=timingPattern.timingPatternID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID];
    NSArray *signalElementList=[dataDoc nodesForXPath:xPathString error:nil];
    NSLog(@"%@",xPathString);
    //    NSMutableArray * signalList=[[[NSMutableArray alloc] init] autorelease];
    for (GDataXMLElement * signalElement in signalElementList) {
        Signal *signal=[[[Signal alloc] init] autorelease];
        NSArray *elementArray=[signalElement elementsForName:@"SignalID"];
        if (elementArray.count>0) {
            [signal setSignalID:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"SignalName"];
        if (elementArray.count>0) {
            [signal setSignalName:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"CycleLength"];
        if (elementArray.count>0) {
            [signal setCycleLength:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Offset"];
        if (elementArray.count>0) {
            [signal setOffset:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetPhase"];
        if (elementArray.count>0) {
            [signal setOffsetPhase:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"OffsetBorE"];
        if (elementArray.count>0) {
            [signal setOffsetBorE:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Location"];
        if (elementArray.count>0) {
            [signal setLocation:[[elementArray objectAtIndex:0] stringValue]];
        }
        elementArray=[signalElement elementsForName:@"Phases"];
        if (elementArray.count>0) {
            NSArray *phaseElementArray=[[elementArray objectAtIndex:0] elementsForName:@"Phase"];
//            NSMutableArray *phaseList=[[[NSMutableArray alloc]init]autorelease];
            for (GDataXMLElement *phaseElement in phaseElementArray) {
                SignalPhase *signalPhase=[[[SignalPhase alloc] init] autorelease];
                NSArray *phaseSubElementArray=[phaseElement elementsForName:@"PhaseID"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseID:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"PhaseMovement"];
                if (phaseSubElementArray) {
                    [signalPhase setPhaseMovement:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"GreenTime"];
                if (phaseSubElementArray) {
                    [signalPhase setGreenTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"YellowTime"];
                if (phaseSubElementArray) {
                    [signalPhase setYellowTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"AllRedTime"];
                if (phaseSubElementArray) {
                    [signalPhase setAllRedTime:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Ring"];
                if (phaseSubElementArray) {
                    [signalPhase setRing:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Barrier"];
                if (phaseSubElementArray) {
                    [signalPhase setBarrier:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                phaseSubElementArray=[phaseElement elementsForName:@"Position"];
                if (phaseSubElementArray) {
                    [signalPhase setPosition:[[phaseSubElementArray objectAtIndex:0] stringValue]];
                }
                NSMutableArray * phaseList=[[[[signal.ringList objectAtIndex:[signalPhase.ring intValue]] barrierList] objectAtIndex:[signalPhase.barrier intValue]] phaseList];
                [phaseList setObject:signalPhase atIndexedSubscript:[signalPhase.position intValue]];
            }
        }        
        
        signal.parentAgencyID=agencyID;
        signal.parentSubSystemID=subSystemID;
        signal.parentTimingPatternID=timingPatternID;
        return signal;
        
        
    }
    return nil;
    
}
+ (BOOL) updateSignal:(Signal *) signal
{
    if (!signal) {
        return false;
    }
    NSString * agencyID=signal.parentAgencyID;
    NSString * subSystemID=signal.parentSubSystemID;
    NSString * timingPatternID=signal.parentTimingPatternID;
    
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]",agencyID,subSystemID,timingPatternID,signal.signalID];      
    NSArray *elements=[dataDoc nodesForXPath:xPathString error:nil];
    
    if (elements.count<=0) {
        [self createSignal:signal];
    }
    for (GDataXMLElement *element in elements) {
        if ([[element elementsForName:@"SignalName"] count]>0) {
            [[[element elementsForName:@"SignalName"] objectAtIndex:0] setStringValue:signal.signalName];
        }
        
        if ([[element elementsForName:@"CycleLength"] count]>0) {
            [[[element elementsForName:@"CycleLength"] objectAtIndex:0] setStringValue:signal.cycleLength];
        }
        if ([[element elementsForName:@"Offset"] count]>0) {
            [[[element elementsForName:@"Offset"] objectAtIndex:0] setStringValue:signal.offset];
        }
        if ([[element elementsForName:@"OffsetPhase"] count]>0) {
            [[[element elementsForName:@"OffsetPhase"] objectAtIndex:0] setStringValue:signal.offsetPhase];
        }
        if ([[element elementsForName:@"OffsetBorE"] count]>0) {
            [[[element elementsForName:@"OffsetBorE"] objectAtIndex:0] setStringValue:signal.offsetBorE];
        }
        if ([[element elementsForName:@"Location"] count]>0) {
            [[[element elementsForName:@"Location"] objectAtIndex:0] setStringValue:signal.location];
        }
        
    }
    
//    for (int i=0; i<signal.ring1.phaseList.count; i++) {
        [self clearPhases:agencyID subSystemID:subSystemID timingPatternID:timingPatternID signalID:signal.signalID];
//    }
    for (SignalRing* signalRing in signal.ringList) {
        for (SignalBarrierGroup *signalBarrier in signalRing.barrierList) {
            for (SignalPhase * phase in signalBarrier.phaseList) {
                if (phase.phaseID) {
                    [self createPhase:phase signal:signal];
                }
            }
        }
    }
    
    return [self saveDataXML];
    

}

+ (NSString *) createSignalID:(NSString *)agencyID subSystemID:(NSString *)subSystemID timingPatternID:(NSString *)timingPatternID
{
    NSArray * elementList=[self getSignalList:agencyID subSystemID:subSystemID timingPatternID:timingPatternID];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Signal *element=[elementList objectAtIndex:i];
        if (maxID<[element.signalID intValue]) {
            maxID=[element.signalID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}

+ (NSString *) createSignalIDofTimingPattern:(TimingPattern *)timingPattern
{
    NSString * agencyID=timingPattern.parentAgencyID;
    NSString * subSystemID=timingPattern.parentSubSystemID;
    NSString * timingPatternID=timingPattern.timingPatternID;
    NSArray * elementList=[self getSignalList:agencyID subSystemID:subSystemID timingPatternID:timingPatternID];
    int maxID=-1;
    for (int i=0; i<elementList.count; i++) {
        Signal *element=[elementList objectAtIndex:i];
        if (maxID<[element.signalID intValue]) {
            maxID=[element.signalID intValue];
        }
    }
    maxID=maxID+1;
    return [NSString stringWithFormat:@"%d",maxID];
}


//Operations of Phases
+ (BOOL)createPhase:(SignalPhase *) phase signal:(Signal *)signal
{
    NSString *agencyID=signal.parentAgencyID;
    NSString *subSystemID=signal.parentSubSystemID;
    NSString *timingPatternID=signal.parentTimingPatternID;
    NSString *signalID=signal.signalID;
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases",agencyID,subSystemID,timingPatternID,signalID];
    
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    GDataXMLElement *phaseElement=[GDataXMLElement elementWithName:@"Phase"];
    GDataXMLElement *phaseIDElement=[GDataXMLElement elementWithName:@"PhaseID" stringValue:phase.phaseID];
    GDataXMLElement *phaseMovementElement=[GDataXMLElement elementWithName:@"PhaseMovement" stringValue:phase.phaseMovement];
    GDataXMLElement *phaseGreenTime=[GDataXMLElement elementWithName:@"GreenTime" stringValue:phase.greenTime];
    GDataXMLElement *phaseYellowTime=[GDataXMLElement elementWithName:@"YellowTime" stringValue:phase.yellowTime];
    GDataXMLElement *phaseAllRedTime=[GDataXMLElement elementWithName:@"AllRedTime" stringValue:phase.allRedTime];
    GDataXMLElement *ringElement=[GDataXMLElement elementWithName:@"Ring" stringValue:phase.ring];
    GDataXMLElement *barrierElement=[GDataXMLElement elementWithName:@"Barrier" stringValue:phase.barrier];
    GDataXMLElement *positionElement=[GDataXMLElement elementWithName:@"Position" stringValue:phase.position];
    [phaseElement addChild:phaseIDElement];
    [phaseElement addChild:phaseMovementElement];
    [phaseElement addChild:ringElement];
    [phaseElement addChild:barrierElement];
    [phaseElement addChild:positionElement];
    [phaseElement addChild:phaseGreenTime];
    [phaseElement addChild:phaseYellowTime];
    [phaseElement addChild:phaseAllRedTime];
    [[parentElements objectAtIndex:0] addChild:phaseElement];
    return [self saveDataXML];

}
+ (BOOL) removePhase:(SignalPhase *)phase signal:(Signal *)signal
{
    NSString *agencyID=signal.parentAgencyID;
    NSString *subSystemID=signal.parentSubSystemID;
    NSString *timingPatternID=signal.parentTimingPatternID;
    NSString *signalID=signal.signalID;
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases",agencyID,subSystemID,timingPatternID,signalID];
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases/Phase[PhaseID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID,phase.phaseID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
    
    
    
}
+ (BOOL) updatePhase:(SignalPhase *)phase signal:(Signal *)signal
{
    NSString *agencyID=signal.parentAgencyID;
    NSString *subSystemID=signal.parentSubSystemID;
    NSString *timingPatternID=signal.parentTimingPatternID;
    NSString *signalID=signal.signalID;
    
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases/Phase[PhaseID=\"%@\"]",agencyID,subSystemID,timingPatternID,signalID,phase.phaseID];
    
    NSArray *elements=[dataDoc nodesForXPath:xPathString error:nil];
    if (elements.count<=0) {
        [self createPhase:phase signal:signal];
        return true;
    }
    
    for (GDataXMLElement *element in elements) {
        if([[element elementsForName:@"PhaseMovement"] count]>0)
        {
            [[[element elementsForName:@"PhaseMovement"] objectAtIndex:0] setStringValue:phase.phaseMovement];
        }
        if([[element elementsForName:@"GreenTime"] count]>0)
        {
            [[[element elementsForName:@"GreenTime"] objectAtIndex:0] setStringValue:phase.greenTime];
        }
        if([[element elementsForName:@"YellowTime"] count]>0)
        {
            [[[element elementsForName:@"YellowTime"] objectAtIndex:0] setStringValue:phase.yellowTime];
        }
        if([[element elementsForName:@"AllRedTime"] count]>0)
        {
            [[[element elementsForName:@"AllRedTime"] objectAtIndex:0] setStringValue:phase.allRedTime];
        }
        if([[element elementsForName:@"Ring"] count]>0)
        {
            [[[element elementsForName:@"Ring"] objectAtIndex:0] setStringValue:phase.ring];
        }
        if([[element elementsForName:@"Barrier"] count]>0)
        {
            [[[element elementsForName:@"Barrier"] objectAtIndex:0] setStringValue:phase.barrier];
        }
        if([[element elementsForName:@"Position"] count]>0)
        {
            [[[element elementsForName:@"Position"] objectAtIndex:0] setStringValue:phase.position];
        }
    }
    
    return [self saveDataXML];

}
+ (BOOL) clearPhases:(NSString *)agencyID subSystemID:(NSString *)subSystemID timingPatternID:(NSString *)timingPatternID signalID:(NSString *)signalID
{
    NSString *xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases",agencyID,subSystemID,timingPatternID,signalID];
    NSArray *parentElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (parentElements.count<=0) {
        return false;
    }
    xPathString=[dataXMLRoot stringByAppendingFormat:@"/Agencies/Agency[AgencyID=\"%@\"]/SubSystems/SubSystem[SubSystemID=\"%@\"]/TimingPatterns/TimingPattern[TimingPatternID=\"%@\"]/Signals/Signal[SignalID=\"%@\"]/Phases/Phase",agencyID,subSystemID,timingPatternID,signalID];
    
    NSArray *childElements=[dataDoc nodesForXPath:xPathString error:nil];
    if (childElements.count<=0) {
        return false;
    }
    for (int i=0; i<childElements.count; i++) {
        [[parentElements objectAtIndex:0] removeChild:[childElements objectAtIndex:i]];
    }
    return [self saveDataXML];
    
    
}


@end
